<?php
ini_set('memory_limit', '-1');
ini_set('max_execution_time', 86400);

define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);

if (file_exists(dirname(__FILE__) . '/defines.php')) {
    include_once dirname(__FILE__) . '/defines.php';
}

if (!defined('_JDEFINES')) {
    define('JPATH_BASE', dirname(__FILE__));
    require_once JPATH_BASE.'/includes/defines.php';
}

require_once JPATH_BASE.'/includes/framework.php';


// Instantiate the application.
$app = JFactory::getApplication('site');

// Initialise the application.
$app->initialise();

require_once JPATH_BASE.DS.'administrator'.DS.'components'.DS.'com_wrd'.DS.'classes'.DS.'utilities'.DS.'reportProvider.php';
require_once JPATH_BASE.DS.'administrator'.DS.'components'.DS.'com_wrd'.DS.'classes'.DS.'utilities'.DS.'pointProvider.php';
require_once JPATH_BASE.DS.'administrator'.DS.'components'.DS.'com_wrd'.DS.'classes'.DS.'PHPExcel.php';

// Init excel
$objPHPExcel = new PHPExcel();

// Set properties
$objPHPExcel->getProperties()->setCreator("Wmc")
                             ->setLastModifiedBy("Wmc")
                             ->setTitle("Detail Statistic")
                             ->setSubject("Detail Statistic")
                             ->setDescription("Detail Statistic")
                             ->setKeywords("Detail Statistic")
                             ->setCategory("Detail Statistic");

// Create a first sheet, representing sales data
$objPHPExcel->setActiveSheetIndex(0);
$activeSheet = $objPHPExcel->getActiveSheet();
$activeSheet->mergeCells('A1:J1');
$activeSheet->setCellValue('A1', 'Detail Statistic Report');
$activeSheet->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$activeSheet->getStyle('A1')->getFont()->setSize(24);
$activeSheet->getStyle('A1')->getFont()->setBold(true);

/************** FILL HEADER **************/
$index = 5;
$activeSheet->setCellValue('A'.$index, 'Member ID');
$activeSheet->setCellValue('B'.$index, 'Name');
$activeSheet->setCellValue('C'.$index, 'Phone');
$activeSheet->setCellValue('D'.$index, 'Email');
$activeSheet->setCellValue('E'.$index, 'Date of birth');
$activeSheet->setCellValue('F'.$index, 'Job');
$activeSheet->setCellValue('G'.$index, 'Company Name');
$activeSheet->setCellValue('H'.$index, 'Location');
$activeSheet->setCellValue('I'.$index, 'Gender');
$activeSheet->setCellValue('J'.$index, 'Created Date');

$activeSheet->setCellValue('K'.$index, 'Reapply Date');

$cols = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K');

foreach($cols as $item)
{
    if($item == 'B')
    {
        setBackgroundColor($activeSheet, $item, 5, 35);
    }
    else if($item == 'G')
    {
        setBackgroundColor($activeSheet, $item, 5, 40);
    }
    else if($item == 'H' || $item == 'D')
    {
        setBackgroundColor($activeSheet, $item, 5, 28);
    }
    else
    {
        setBackgroundColor($activeSheet, $item, 5, 18);   
    }
}

// End init excel

/******** Query Data ********/  
$db = JFactory::getDbo();
$conditions = array();
$conditions['statistic_by'] = strval($_GET['st']);
$conditions['date_from'] = strval($_GET['f']);
$conditions['date_to'] = strval($_GET['t']);
$conditions['sex'] = strval($_GET['s']);
$conditions['age'] = strval($_GET['a']);
$conditions['job'] = strval($_GET['j']);
$conditions['location'] = strval($_GET['location']);

$activeSheet->setCellValue('A2', 'Date From' );                
$activeSheet->setCellValue('B2', date("d-m-Y",strtotime($conditions['date_from'])) ); 
$activeSheet->setCellValue('C2', 'Date To' );                
$activeSheet->setCellValue('D2', date("d-m-Y",strtotime($conditions['date_to'])) ); 
		
$query = reportProvider::memberStatisticFilter($conditions);
if(intval($_GET['l']) > 0)
{
    $db->setQuery($query['items'], 0, intval($_GET['l']) );   
}
else
{
    $db->setQuery($query['items'] );   
}
$data['items'] = $db->loadObjectList();

$db->setQuery($query['total']) ;
$data['total'] = count($db->loadObjectList());    


if(!empty($data))
{
    $activeSheet->mergeCells('A3:J3');
    $activeSheet->setCellValue('A3', 'Total: '.$data['total'].'. Display top: '.count($data['items']));   
    $style = $activeSheet->getStyle('A3')->getFont();
    $style->setSize(16);
    $style->setBold(true);
    $style->setColor( new PHPExcel_Style_Color( 'CC0000' ) );
    
    /*********** BIND TO EXCEL ***********/
    $index = 6;
    $data = $data['items'];
    $size = count($data);
    for($i=0; $i<$size; $i++)
    {
        $activeSheet->setCellValue('A'.$index, 'V'.$data[$i]->member_id);            
            
        $activeSheet->setCellValue('B'.$index, $data[$i]->l_name.' '.$data[$i]->f_name);
        
        
        $activeSheet->setCellValueExplicit('C'.$index, $data[$i]->phone, PHPExcel_Cell_DataType::TYPE_STRING);     
        $activeSheet->getStyle('C'.$index)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                     
        $activeSheet->setCellValue('D'.$index, $data[$i]->email);                
        $activeSheet->setCellValue('E'.$index, (strtotime($data[$i]->dob)?date("d-m-Y",strtotime($data[$i]->dob)):""));   
        $activeSheet->getStyle('E'.$index)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                 
        $activeSheet->setCellValue('F'.$index, $data[$i]->job);            
        $activeSheet->setCellValue('G'.$index, $data[$i]->company);            
        $activeSheet->setCellValue('H'.$index, $data[$i]->distric);           
         
        $activeSheet->setCellValue('I'.$index, ucfirst($data[$i]->gender));            
        $activeSheet->getStyle('I'.$index)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $activeSheet->setCellValue('J'.$index, (strtotime($data[$i]->created_date)?date("d-m-Y",strtotime($data[$i]->created_date)):""));            
        $activeSheet->getStyle('J'.$index)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        
		 $activeSheet->setCellValue('K'.$index,(strtotime($data[$i]->reapply_date)?date("d-m-Y H:i:s",strtotime($data[$i]->reapply_date)):"") ); 
        $index++;
    }
    unset($data);
    unset($data);
}

$fileName = 'detail_statistic_'.date('m-d-Y');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(JPATH_BASE.DS.'tmp'.DS.$fileName.'.xlsx');

$fullPath = JPATH_ROOT.DS.'tmp'.DS.$fileName.'.xlsx';
$fsize = filesize($fullPath);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$fileName.'.xlsx"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $fsize);
ob_clean();
flush();
readfile( $fullPath );
exit;          


function setBackgroundColor(&$activeSheet, $colName, $colIndex, $width=15)
{
    $fill = $activeSheet->getStyle($colName.$colIndex)->getFill();
    $fill->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
    $fill->getStartColor()->setARGB('cc99ff');  
    $activeSheet->getColumnDimension($colName)->setWidth($width);    
    
    $style = $activeSheet->getStyle($colName.$colIndex);
    $style->getFont()->setSize(12);
    //$style->getFont()->setBold(true);
    $style->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
}
